<template>
  <div class="worktable-frame-page">
    <div class="notice" v-if="env === 'development' || env === 'staging'" @click="getCanvasData">
      当前页面从 [商户] 平台的流程模板进入，（仅在测试环境和开发环境显示此提示，当前：{{env}}）
    </div>
    <iframe id="worktableFrame"
            class="worktable-frame"
            ref="worktableFrame"
            title="编辑模型"
            :src="src"
            @load="handleIFrameLoaded"
    ></iframe>
  </div>
</template>

<script lang="ts" setup>
/**
 * @deprecated 不使用
 */
import useMerchantSrc from "./composition/useMerchantSrc";
import useIframeCommunicate from "./composition/useIframeCommunicate";
import {getModelData} from "@/api/flowModel";
import {IModelInfoData} from "@/api/modules/flowModel";

const router = useRouter()
const route = useRoute()
const store = useStore()

const worktableFrame = ref<HTMLIFrameElement>()

const {src, env, host: merchantHost} = useMerchantSrc({
  pathName: '/merchant/',
  hash: '#/flow/auto/marketingProcess/workTable',
  query: route.query
})

const handleIFrameLoaded = () => {
  console.log('iframe loaded !!!')
}

// worktable 设置message监听后会主动post这个方法
const worktableReady = () => {
  console.log('worktable ready !!!')

  getCanvasData()
}

const getCanvasData = async () => {
  const id = route.query.modelId as string
  if (!id) {
    return
  }

  const rs = await getModelData({id})

  const iframeElement = worktableFrame.value
  if (!iframeElement) {
    ElMessage.warning('框架未初始化')
    return
  }

  messagePoster(iframeElement, methodMessageCreator('iframe_getCanvasData', rs))
}

const {messageListener, methodMessageCreator, messagePoster} = useIframeCommunicate({getCanvasData, worktableReady})

onMounted(() => {
  window.addEventListener('message', messageListener, false)
})

onBeforeUnmount(() => {
  window.removeEventListener('message', messageListener)
})
</script>

<style scoped lang="scss">
.notice {
  background: blue;
  color: white;
  position: fixed;
  top: 0;
  right: 0;
  font-size: 12px;
}

.worktable-frame-page {
  height: 100vh;
}

.worktable-frame {
  width: 100%;
  height: 100%;
  display: block;
  border: unset;
  margin: unset;
  padding: unset;
  overflow: hidden;
}
</style>
